import xlrd
import re
from zentao.xmind import Xmind

class Excel(object):
    
    def __init__(self, import_type, path):
        # 1：导入用例库模块，2：导入用例模块-后续更新
        self.choice_type = {'1': {'title': Xmind.get_file_data(path, 'title')},
                            '2': None}
        self.title = 'Excel用例导入禅道'
        
        if import_type == '1':
            # todo x_mind导入用例库
            pass
        elif import_type == '2':
            title = 'Excel用例导入禅道'
            data, msg = Excel.upload_excel(path)
    
    @classmethod
    def get_step(cls, config_dict, type, step_str):
        """操作步骤按填写的步骤顺序生成
        :param config_dict:
        :param type:
        :param step_str:
        :return:
        """
        step_str = re.sub(r"\r\s*\n", "&", step_str)
        steps = step_str.split("\n")
        for step in steps:
            if step != "":
                step_index = int(step.split(".", 1)[0].strip())
                step_data = step.split(".", 1)[1].replace("\n", "").strip()
                # 判断是否存在子级，有进行处理
                if re.match("{step_index}\.\d+", step_data):
                    for substep in step_data.split("&"):
                        substep_list = (re.split("({step_index}+\.\d+)", substep.strip()))
                        substep_list = list(filter(None, substep_list))
                        if not (re.match("{step_index}+\.\d+", substep_list[0])):
                            # 处理分组名称,如是结果就不需要值
                            if type != 'expects':
                                substep_data = substep_list[0]
                                config_dict["{type}[{step_index}]"] = substep_data
                            substep_list.remove(substep_list[0])
                        if substep_list != []:
                            # 有子级处理子级格式处理
                            substep_index = float(substep_list[0])
                            substep_data = substep_list[1]
                            config_dict["{type}[{substep_index}]"] = substep_data
                            if type == 'steps':
                                # 是步骤需要添加步骤类型，子级item，父级group
                                config_dict["stepType[{substep_index}]"] = "item"
                                config_dict["stepType[{step_index}]"] = "group"
                    
                    if "{type}[{step_index}]" not in config_dict.keys():
                        # 有子级，分组名不存在或为空，赋值分组
                        if type == 'expects':
                            config_dict["{type}[{step_index}]"] = ''
                        else:
                            config_dict["{type}[{step_index}]"] = '分组'
                else:
                    step_data = re.sub("&", r"\r\n", step_data)
                    config_dict["{type}[{step_index}]"] = step_data
                    if type == 'steps':
                        config_dict["stepType[{step_index}]"] = "step"
        return config_dict
    
    @classmethod
    def upload_excel(cls, file):
        """excel格式生成成禅道接口的入参数据
        :param file:
        :return:
        """
        data = xlrd.open_workbook(file)
        case_data = data._sheet_list[0]._cell_values
        data_json = []
        problem_statement = []
        for row_index, data in enumerate(case_data[1:], 2):
            config_dict = {"product": 0, "module": 0, "title": 'null', "precondition": 'null',
                           "steps[1]": '分组',
                           'stepType[1]': 'group',
                           "expects[1]": '', "pri": 3}
            column_error = []
            for index, title in enumerate(case_data[0], 1):
                try:
                    if title == '所属模块':
                        modules = data[case_data[0].index(title)].split("#")[1][:-1]
                        config_dict['module'] = int(modules.split("-")[1].strip())
                        config_dict['product'] = int(modules.split("-")[0].strip())
                    elif title == '用例标题':
                        config_dict['title'] = data[case_data[0].index(title)]
                    elif title == '前置条件':
                        config_dict['precondition'] = data[case_data[0].index(title)]
                    elif title == '步骤':
                        cls.get_step(config_dict, 'steps', data[case_data[0].index(title)])
                    elif title == '预期':
                        cls.get_step(config_dict, 'expects', data[case_data[0].index(title)])
                    elif title == '优先级':
                        config_dict['pri'] = int(data[case_data[0].index(title)])
                    elif title == '用例库':
                        config_dict['lib'] = data[case_data[0].index(title)]
                except Exception as e:
                    column_error.append(str(index))
                    print(str(e))
                    continue
            if not column_error:
                # 步骤有预期，没有结果，结果生成为空
                steps_indexs = []
                expects_indexs = []
                for key in config_dict.keys():
                    if re.match("steps[.*?]*", key):
                        steps_indexs.append(re.findall(r"\d+\.?\d*", key)[0])
                    if re.match("expects[.*?]*", key):
                        expects_indexs.append(re.findall(r"\d+\.?\d*", key)[0])
                for step_index in steps_indexs:
                    if step_index not in expects_indexs:
                        config_dict['expects[{step_index}]'] = ''
                data_json.append(config_dict)
            else:
                problem_statement.append("第{row_index}行的第{'、'.join(column_error)}列格式存在错误")
        print(data_json)
        print(problem_statement)
        if problem_statement:
            problem_statement = '总共需要导入的用例总数{}条，导入失败的用例数{}条，具体失败的内容如下'. \
                format(len(case_data[1:]), len(problem_statement))
            return data_json, problem_statement
        else:
            return data_json, "成功"
    
    @classmethod
    def handle_data(cls, data):
        """处理excel数据
        :param data:
        :return:
        """
        # 处理优先级.转str
        pri = data.get('pri')
        if isinstance(pri, float):
            pri = str(pri).split('.')[0]
        data['pri'] = pri
        steps = data.get('steps')
        expects = data.get('expects')
        # son_expects = expects[s]
        for s in range(1, len(steps) + 1):
            son_steps = steps[s]
            son_expects = expects[s]
            # 有分组
            if isinstance(son_steps, dict):
                data['steps[{}]'.format(s)] = '分组{}'.format(s)
                data['stepType[{}]'.format(s)] = 'group'
                data['expects[{}]'.format(s)] = ''
                for num in son_steps:
                    # 步骤、结果
                    if isinstance(son_expects, dict):
                        data['expects[{}]'.format(num)] = son_expects.get(num)
                    elif str(num).split('.')[1] > '1':
                        data['expects[{}]'.format(num)] = None
                    else:
                        data['expects[{}]'.format(num)] = son_expects
                    data['steps[{}]'.format(num)] = son_steps.get(num)
                    data['stepType[{}]'.format(num)] = 'item'
            else:
                # 只有步骤、结果
                case_name = steps.get(s)
                data['steps[{}]'.format(s)] = case_name
                data['stepType[{}]'.format(s)] = 'step'
                data['expects[{}]'.format(s)] = expects.get(s)
        
        del data['steps']
        del data['expects']
        del data['lib']
        return data
